<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>美食点评 - 预签名URL上传演示</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      margin: 20px;
      background-color: #f4f4f9;
      color: #333;
    }
    .container {
      max-width: 600px;
      margin: 20px auto;
      padding: 25px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }
    .form-group {
      margin-bottom: 18px;
    }
    label {
      display: block;
      margin-bottom: 6px;
      font-weight: bold;
      color: #555;
    }
    input[type="text"],
    input[type="number"],
    textarea,
    input[type="file"] {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      box-sizing: border-box; /* Important for consistent sizing */
      font-size: 1rem;
    }
    textarea {
      resize: vertical; /* Allow vertical resizing */
      min-height: 80px;
    }
    input[type="file"] {
        padding: 5px; /* Adjust padding for file input */
    }
    button {
      display: inline-block;
      padding: 12px 20px;
      background-color: #007bff; /* Blue */
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 1rem;
      transition: background-color 0.3s ease;
    }
    button:hover {
      background-color: #0056b3; /* Darker blue */
    }
    button:disabled {
        background-color: #cccccc;
        cursor: not-allowed;
    }
    .status {
      margin-top: 20px;
      padding: 12px;
      border-radius: 4px;
      font-size: 0.95rem;
    }
    .status.info {
        background-color: #e2f3ff; /* Light blue for info */
        color: #004085;
        border: 1px solid #b8daff;
    }
     .status.success {
        background-color: #d4edda; /* Light green for success */
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .status.error {
        background-color: #f8d7da; /* Light red for error */
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    /* Basic responsive adjustments */
    @media (max-width: 600px) {
        .container {
            margin: 10px;
            padding: 15px;
        }
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>📝 美食点评 - 预签名URL上传模式</h1>

    <div class="form-group">
      <label for="userId">学号：</label>
      <input type="text" id="userId" placeholder="请输入你的学号" required>
    </div>

    <div class="form-group">
      <label for="userName">姓名/昵称：</label>
      <input type="text" id="userName" placeholder="（选填）">
    </div>

    <div class="form-group">
      <label for="restaurantName">餐厅名称：</label>
      <input type="text" id="restaurantName" placeholder="例如：东区均园食堂二楼" required>
    </div>

    <div class="form-group">
      <label for="restaurantLocation">餐厅位置：</label>
      <input type="text" id="restaurantLocation" placeholder="例如：靠近图书馆" required>
    </div>

    <div class="form-group">
      <label for="dishName">推荐菜品：</label>
      <input type="text" id="dishName" placeholder="（选填）例如：麻辣香锅">
    </div>

    <div class="form-group">
      <label for="rating">评分 (1-5)：</label>
      <input type="number" id="rating" min="1" max="5" placeholder="输入1到5的整数" required>
    </div>

    <div class="form-group">
      <label for="reviewText">评价内容：</label>
      <textarea id="reviewText" rows="4" placeholder="分享你的美食体验..." required></textarea>
    </div>

    <div class="form-group">
      <label for="images">上传图片：</label>
      <input type="file" id="images" multiple accept="image/jpeg, image/png, image/gif">
    </div>

    <button id="submitBtn">🚀 提交评价</button>

    <div class="status" id="status">请填写信息并提交</div>
  </div>

  <script>
  const submitBtn = document.getElementById('submitBtn');
const statusElement = document.getElementById('status');
const fileInput = document.getElementById('images');

// --- 配置 ---
const API_BASE_URL = 'http://192.168.147.21:3000';

async function getUploadUrl(filename, contentType) {
  const urlEndpoint = `${API_BASE_URL}/api/upload-url?filename=${encodeURIComponent(filename)}&contentType=${encodeURIComponent(contentType)}`;
  const response = await fetch(urlEndpoint);
  if (!response.ok) {
    throw new Error(`Failed to get upload URL. Status: ${response.status}`);
  }
  return await response.json();
}

async function uploadFile(uploadUrl, file) {
  const response = await fetch(uploadUrl, {
    method: 'PUT',
    headers: {
      'Content-Type': file.type
    },
    body: file
  });
  if (!response.ok) {
    throw new Error(`Failed to upload file. Status: ${response.status}`);
  }
}

async function getUploadComplete(fileKey) {
  const response = await fetch(`${API_BASE_URL}/api/upload-complete`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ fileKey })
  });
  if (!response.ok) {
    throw new Error(`Failed to get upload complete URL. Status: ${response.status}`);
  }
  return await response.json();
}

async function submitReview(userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imagePath) {
  const endpoint = `${API_BASE_URL}/api/reviews`;
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      userId,
      userName: userName || null, // 如果为空则发送 null
      restaurantName,
      restaurantLocation,
      dishName: dishName || null, // 如果为空则发送 null
      rating,
      reviewText,
      imagePath: imagePath || null // 如果为空则发送 null
    })
  });
  if (!response.ok) {
    throw new Error(`Failed to submit review. Status: ${response.status}`);
  }
  return await response.json();
}

submitBtn.addEventListener('click', async function() {
  submitBtn.disabled = true;
  statusElement.textContent = '⏳ 正在处理，请稍候...';
  statusElement.className = 'status info';

  try {
    // 1. 收集表单数据
    const userId = document.getElementById('userId').value.trim();
    const userName = document.getElementById('userName').value.trim();
    const restaurantName = document.getElementById('restaurantName').value.trim();
    const restaurantLocation = document.getElementById('restaurantLocation').value.trim();
    const dishName = document.getElementById('dishName').value.trim();
    const rating = parseInt(document.getElementById('rating').value, 10);
    const reviewText = document.getElementById('reviewText').value.trim();
    const files = fileInput.files;

    // 2. 验证必填字段
    if (!userId || !restaurantName || !restaurantLocation || !rating || !reviewText) {
      statusElement.textContent = '⚠️ 请填写所有必填字段 (学号, 餐厅名, 位置, 评分, 内容)';
      statusElement.className = 'status error';
      submitBtn.disabled = false;
      return;
    }
    if (isNaN(rating) || rating < 1 || rating > 5) {
      statusElement.textContent = '⚠️ 评分必须是 1 到 5 之间的整数';
      statusElement.className = 'status error';
      submitBtn.disabled = false;
      return;
    }

    // 3. 上传图片（如果有选择）
    let uploadedImagePaths = [];
    if (files.length > 0) {
      statusElement.textContent = `⏳ 准备上传 ${files.length} 张图片...`;
      statusElement.className = 'status info';
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const key = await getUploadUrl(file.name, file.type);
        await uploadFile(key.uploadUrl, file);
        const result = await getUploadComplete(key.fileKey);
        uploadedImagePaths.push(result.imagePath);
        statusElement.textContent = `[${i + 1}/${files.length}] 图片 "${file.name}" 上传成功! 正在获取路径...`;
        statusElement.className = 'status info';
      }
      statusElement.textContent = `✅ 所有 ${files.length} 张图片上传完成!`;
      statusElement.className = 'status success';
    } else {
      statusElement.textContent = 'ℹ️ 未选择图片。';
      statusElement.className = 'status info';
    }

    // 4. 提交评价数据
    statusElement.textContent = '⏳ 正在提交评价信息...';
    statusElement.className = 'status info';
    const imagePathField = uploadedImagePaths.length > 0 ? uploadedImagePaths.join(',') : '';
    const reviewData = await submitReview(userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imagePathField);
    statusElement.textContent = `🎉 评价提交成功！评价ID: ${reviewData.id}. ${reviewData.message || ''}`;
    statusElement.className = 'status success';
  } catch (error) {
    statusElement.textContent = `❌ 操作失败: ${error.message}`;
    statusElement.className = 'status error';
  } finally {
    submitBtn.disabled = false;
  }
});


  </script>
</body>
</html>
